﻿/*
 * Autore: Paolo Farina
 */

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using RecipesManager.Data;
using RecipesManager.Data.Operations;
using RecipesManager.MainControls.EventSubControls;

namespace RecipesManager.MainControls
{

    public class EventElems
    {
        public EventElems(int id, string name, string date)
        {
            Id = id;
            Name = name;
            Date = date;
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Date { get; set; }

        // override object.Equals
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            return ((EventElems) obj).Id.Equals(this.Id);
        }

        //TODO mi sembra che questo non sia un metodo corretto per calcolare il hashcode.. da confermare
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }


    /// <summary>
    /// Logica di interazione per EventUserControl.xaml
    /// </summary>
    public partial class EventUserControl : UserControl, IMyUserControls, ISwitchable
    {
        EventMainPane _actualPanel = null;
        ObservableCollection<EventElems> eventElems=null;
        ObservableCollection<EventElems> eventEndedElems = null;


        public string SectionName { get { return (string)Application.Current.FindResource("EventsSectionLabel"); } }
        
        public EventUserControl()
        {
            InitializeComponent();
            eventElems=new ObservableCollection<EventElems>();
            eventEndedElems=new ObservableCollection<EventElems>();
            Refresh_Event_List();
            lw_eventi.ItemsSource = eventElems;
            lw_eventiPassati.ItemsSource = eventEndedElems;
            lw_eventiPassati.Visibility=Visibility.Collapsed;
            bt_delete.IsEnabled = false;

            CommandManager.RegisterClassCommandBinding(typeof(EventUserControl), _savebinding);
            CommandManager.RegisterClassCommandBinding(typeof(EventUserControl), _closebinding);
            Keyboard.Focus(this);
        }


        void Refresh_Event_List(string id = "")
        {
            lw_eventi.SelectedItem = null;
            var count = lw_eventi.Items.Count;
            
            eventElems.Clear();
            eventEndedElems.Clear();
            foreach (var e in Manager.Events)
            {
                var date = "";
                if (!e.Date.GetValueOrDefault().Equals(new DateTime())) date = e.Date.GetValueOrDefault().ToString();

                if(!e.HasEnded)
                {
                    if (e.Name.ToLower().Contains(tb_search.Text.ToLower()))
                        eventElems.Add(new EventElems(e.Id,e.Name,date));
                }
                else eventEndedElems.Add(new EventElems(e.Id, e.Name, date));
            }
            



            if (id!=null && !id.Equals("")) lw_eventi.SelectedItem = id;
        }

        public bool Save_Context()
        {
            
            if (_actualPanel != null && _actualPanel.bt_salva.IsEnabled)
            {
                var result = MessageBox.Show((string)Application.Current.FindResource("want_to_save"),
                                             (string)Application.Current.FindResource("notification_dialog_type"),
                                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                        var resSave=_actualPanel.Save();
                        if (!resSave) _actualPanel.bt_salva.IsEnabled = false;
                        Refresh_Event_List(_actualPanel.tb_nomeEvento.Text);
                        if (!resSave) _actualPanel.bt_salva.IsEnabled = true;
                        Mouse.OverrideCursor = null;
                        break;
                    case MessageBoxResult.No:
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            
            return true;

        }

        void Close_Context()
        {
            if (_actualPanel != null && _actualPanel.bt_salva.IsEnabled)
            {
                var result = MessageBox.Show((string)Application.Current.FindResource("want_to_save_before_closing"),
                                             (string)Application.Current.FindResource("notification_dialog_type"),
                                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        _actualPanel.Save();
                        _actualPanel = null;
                        eventContentPane.Content = _actualPanel;
                        bt_delete.IsEnabled = false;
                        lw_eventi.SelectedItem = null;
                        lw_eventiPassati.SelectedItem = null;
                        Refresh_Event_List();
                        break;
                    case MessageBoxResult.No:
                        _actualPanel = null;
                        eventContentPane.Content = _actualPanel;
                        bt_delete.IsEnabled = false;
                        lw_eventi.SelectedItem = null;
                        lw_eventiPassati.SelectedItem = null;
                        break;
                    case MessageBoxResult.Cancel:
                        break;
                }
            }
            else
            {
                _actualPanel = null;
                eventContentPane.Content = _actualPanel;
                bt_delete.IsEnabled = false;
                lw_eventi.SelectedItem = null;
                lw_eventiPassati.SelectedItem = null;
            }
        }

        public bool CheckEventOnDelete(int id)
        {
            IEnumerable<string> canDeleteMessage;

            var canDelete = Operations.CanRemoveEvent(id, out canDeleteMessage);
            var msgFromCanRemove = canDeleteMessage.Aggregate("", (current, m) => current + (Environment.NewLine + m));
            var msgStr = "";


            if (canDelete)
            {
                msgStr += (string)Application.Current.FindResource("ElementCanBeDeleted");
                if (!msgFromCanRemove.Equals("")) msgStr += " " + (string)Application.Current.FindResource("ElementIsUsedBy") + msgFromCanRemove;

                var dresult = MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.YesNo, MessageBoxImage.Warning);

                switch (dresult)
                {
                    case MessageBoxResult.Yes:
                        return true;
                    case MessageBoxResult.No:
                        return false;
                }
            }
            else
            {
                msgStr = (string)Application.Current.FindResource("ElementCannotBeDeleted") + msgFromCanRemove;
                MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }

        #region ButtonHandlers

        public void Bt_Back_Click(object sender, RoutedEventArgs e)
        {
            Switcher.Switch(new MainMenu());
        }
        
        public void Bt_Search_Click(object sender, RoutedEventArgs e)
        {
            Refresh_Event_List();
        }

        public void Bt_Clear_Search_Click(object sender, RoutedEventArgs e)
        {
            tb_search.Text = "";
            Refresh_Event_List();
        }

        public void Bt_Add_Click(object sender, RoutedEventArgs e)
        {
            if (_actualPanel != null && !Save_Context()) return;

            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            this.eventContentPane.Content = new EventMainPane("", 0);
            _actualPanel = (EventMainPane)eventContentPane.Content;
            Mouse.OverrideCursor = null;
        }

        public void Bt_Delete_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            if (lw_eventi.SelectedValue != null && CheckEventOnDelete(((EventElems)lw_eventi.SelectedValue).Id))
            {
                Manager.Events.Remove(((EventElems)lw_eventi.SelectedValue).Id);
                Refresh_Event_List();
                eventContentPane.Content = null;
                _actualPanel = null;
            }
            else if (lw_eventiPassati.SelectedValue!=null && CheckEventOnDelete(((EventElems)lw_eventiPassati.SelectedValue).Id))
            {
                Manager.Events.Remove(((EventElems)lw_eventiPassati.SelectedValue).Id);
                Refresh_Event_List();
                eventContentPane.Content = null;
                _actualPanel = null;
            }
            Mouse.OverrideCursor = null;
        }
        
        public void Lb_Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            var list = (ListView) sender;
            if (list.Name.EndsWith("Passati")) lw_eventi.SelectedItem = null;
            else lw_eventiPassati.SelectedItem = null;
            bt_delete.IsEnabled = list.SelectedItem != null;
            if (!Save_Context() || list.SelectedValue == null) { Mouse.OverrideCursor = null; return; }
            _actualPanel = new EventMainPane(((EventElems)list.SelectedValue).Name, ((EventElems)list.SelectedValue).Id);
            eventContentPane.Content = _actualPanel;
            Mouse.OverrideCursor = null;
        }

        private void Tb_ClosedEvent_Click(object sender, RoutedEventArgs e)
        {

            var tb = (ToggleButton)sender;
            if (tb.IsChecked.GetValueOrDefault())
            {
                lw_eventiPassati.Visibility=Visibility.Visible;
            }
            else
            {
                lw_eventiPassati.Visibility = Visibility.Collapsed;
                this.UpdateLayout();
            }


        }

        void Tb_search_OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            e.Handled = true;
            bt_search.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
        }

        #endregion

        #region OtherHandlers

        private void Lw_Eventi_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var listView = sender as ListView;
            if (listView == null)
                return;

            var gridView = listView.View as GridView;
            if (gridView == null)
                return;

            var workingWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;

            if (listView.Equals(lw_eventi))
            {
                var col1 = 0.50;
                var col2 = 0.50;

                gridView.Columns[0].Width = workingWidth * col1;
                gridView.Columns[1].Width = workingWidth * col2;
 
            } 
        }

        private void sl_dim_ValueChanged(object sender, RoutedEventArgs e)
        {
            var sl = (MenuItem) sender;

            if (sl.Name.EndsWith("Dim"))
            {
                zoomAum.IsEnabled = true;
                FontSize = FontSize - 2;
                if(FontSize<=10)
                {
                    zoomDim.IsEnabled = false;
                }
            }
            else
            {
                zoomDim.IsEnabled = true;
                FontSize = FontSize + 2;
                if (FontSize >= 22)
                {
                    zoomAum.IsEnabled = false;
                }
            }

            
        }

        #endregion
        
        #region ISwitchable Members

        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region SaveCommandRegion

        readonly CommandBinding _savebinding = new CommandBinding(ApplicationCommands.Save, CommandSaveHandler);

        static void CommandSaveHandler(object target, ExecutedRoutedEventArgs e)
        {
            var id = (EventElems)((EventUserControl)target).lw_eventi.SelectedItem;
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            ((EventUserControl)target)._actualPanel.Save();
            ((EventUserControl)target).Refresh_Event_List(((EventUserControl)target)._actualPanel.tb_nomeEvento.Text);
            Mouse.OverrideCursor = null;
            

        }

        #endregion

        #region CloseCommandRegion

        readonly CommandBinding _closebinding = new CommandBinding(ApplicationCommands.Close, CommandCloseHandler);

        static void CommandCloseHandler(object target, ExecutedRoutedEventArgs e)
        {

            ((EventUserControl)target).Close_Context();
        }

        #endregion

        
    }
}
